const renderer = require('vue-server-renderer').createRenderer()
const express = require('express')()
const createApp = require('./dist/bundle.server.js')['default']

express.get('*', (req, res) => {
  const context = {
    url: req.url
  }

  createApp(context).then(app => {
    renderer.renderToString(app, (err, html) => {
      if (err) {
        return res.status(500).end(err)
      }
      res.send(`
        <!DOCTYPE html>
        <html lang="zh">
          <head>
            <meta charset="UTF-8">
            <title>Yochia Vue SSR 测试页面</title>
          </head>
          <body>
            ${html}
          </body>
        </html>
      `)
    }, err => {
      if (err.status === 404) {
        res.status(404).end('该页面不存在')
      }
    })
  }).catch(error => {
    return res.status(500).end(error)
  })
})

express.listen(8080, () => {
  console.log('服务器已启动，请访问localhost:8080')
})
